import React, { PureComponent } from "react";
import { StyleSheet, Modal, View, AppState, NativeModules, ToastAndroid } from "react-native";
import { scaleSize, setSpText } from "../Utils/ToolUtils";
import { Colors } from "../Theme/TTheme";
import { TText } from "./WidgetDefault";
import CodePush from "react-native-code-push";
import { CodePushDeploymentKey, HOTUPDATE } from "../Storage/Const";

function identifyDebugDevelopmentEnvironment() {
    try{
        const { scriptURL } = NativeModules.SourceCode
        if(scriptURL && scriptURL.length > 0) {
            const devSplit = scriptURL.split('&');
            if(devSplit.length > 1) {
                return devSplit[1] == 'dev=true';
            }
        }
        return false;
    }catch(error) {
    }
    return false;
}

export default class CodePushUpgradeDialog extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            progress: 0,
            visible: false,
            appState: AppState.currentState,
        };
        this.updateTimer = null;
    }

    componentDidMount() {
        this.appChangeListener = AppState.addEventListener('change', this._handleAppStateChange);
        this.checkUpdate();
    }

    componentWillUnmount() {
        //AppState.removeEventListener('change', this._handleAppStateChange);
        if(this.appChangeListener) {
            this.appChangeListener.remove();
            this.appChangeListener = null;
        }
        if(this.updateTimer) {
            clearTimeout(this.updateTimer);
            this.updateTimer = null;
        }
    }

    _handleAppStateChange = (nextAppState) => {
        if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
            this.checkUpdate();
        }
        this.setState({appState: nextAppState});
    };

    checkUpdate = () => {
        if((!identifyDebugDevelopmentEnvironment()) && HOTUPDATE) {
            CodePush.checkForUpdate(CodePushDeploymentKey).then((upgrade)=>{
                if(upgrade) {
                    this.setState({
                        visible:true
                    },()=>{
                        this.update();
                    });
                } else {
                    CodePush.notifyAppReady();
                }
            }).catch(err=>{
                console.log("err", err);
            });
        } else {
            console.log("debug model or unhotupdate");
        }
    }

    update = () => {
        if(this.updateTimer) {
            clearTimeout(this.updateTimer);
        }
        this.updateTimer = setTimeout(()=>{
            this.setState({visible:false});
        }, 1000 * 60 * 5);
        CodePush.allowRestart();
        CodePush.sync({deploymentKey:CodePushDeploymentKey,installMode: CodePush.InstallMode.IMMEDIATE}, (syncStatus)=>{
            switch (syncStatus) {
                case CodePush.SyncStatus.UP_TO_DATE:
                    this.setState({visible: false});
                    break;
                case CodePush.SyncStatus.UNKNOWN_ERROR:
                    this.setState({visible: false});
                    ToastAndroid.show('更新出错，请稍后重试！', ToastAndroid.SHORT);
                    break;
                case CodePush.SyncStatus.CHECKING_FOR_UPDATE:
                case CodePush.SyncStatus.DOWNLOADING_PACKAGE:
                case CodePush.SyncStatus.AWAITING_USER_ACTION:
                case CodePush.SyncStatus.INSTALLING_UPDATE:
                case CodePush.SyncStatus.UPDATE_IGNORED:
                case CodePush.SyncStatus.UPDATE_INSTALLED:
                    break;
                default:
                    break;
                }
        }, (progress)=>{
            console.log("progress:",progress);
            let percent = Math.round(parseFloat(progress.receivedBytes / progress.totalBytes) * 100);
            this.setState({
                progress: percent,
            },()=>{
                if(percent >= 100) {
                    this.setState({
                        visible:false
                    }, ()=>{
                        clearTimeout(this.updateTimer);
                        this.updateTimer = null;
                    })
                }
            });
        });
    }

    render() {
        return <Modal
                animationType="none"
                transparent={true}
                visible={this.state.visible}
                onRequestClose={() => {
                }}>
                <View style={styles.container}>
                        <View style={styles.modalContainer}>
                            <View style={styles.headerContainer}>
                                <TText h3>{"资源更新中，请稍候"}</TText>
                            </View>
                            <View style={styles.bodyContainer}>
                                <TText style={{color:Colors.text4_color, fontSize: setSpText(40)}}>{this.state.progress+"%"}</TText>
                            </View>
                        </View>
                    </View>
            </Modal>
    }
}

const styles = StyleSheet.create({
    container:{
        flex: 1,
        backgroundColor: 'rgba(0,0,0,0.5)',
        justifyContent: 'center',
        alignItems: 'center',
        opacity: 1
    },
    modalContainer:{
        backgroundColor: Colors.white,
        borderRadius: scaleSize(8),
        width: scaleSize(376),
        justifyContent: 'center',
    },
    headerContainer:{
        paddingHorizontal: scaleSize(30),
        paddingVertical:scaleSize(30),
        flexDirection:'row',
        justifyContent:'center',
        alignItems:'center',
    },
    bodyContainer:{
        paddingHorizontal: scaleSize(30),
        paddingVertical:scaleSize(30),
        justifyContent:'center',
        alignItems:'center',
    },
});